package com.tanhua.app.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.api.db.UserApi;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.FriendsApi;
import com.tanhua.api.mongo.RecommentApi;
import com.tanhua.api.mongo.UserLikeApi;
import com.tanhua.api.mongo.VisitorsApi;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mogo.Friend;
import com.tanhua.domain.mogo.UserLike;
import com.tanhua.domain.mogo.Visitors;
import com.tanhua.domain.vo.*;
import com.tanhua.template.AipFaceTemplate;
import com.tanhua.template.HuanXinTemplate;
import com.tanhua.template.OssTemplate;
import com.tanhua.template.SmsTemplate;
import com.tanhua.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class UserService {
    @Reference
    private UserApi userApi;
    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Reference
    private FriendsApi friendsApi;
    @Reference
    private UserLikeApi userLikeApi;
    @Reference
    private VisitorsApi visitorsApi;
    @Reference
    private RecommentApi recommentApi;

    //根据token从redis中获取注册用户（抽取工具）
    public User fromRedisUser(String token) {

        String json_user = stringRedisTemplate.opsForValue().get("TOKEN_" + token);
        //json--java对象
        User user = JSON.parseObject(json_user, User.class);
        //设置token失效时间
        stringRedisTemplate.opsForValue().set("TOKEN_"+token,json_user,1,TimeUnit.DAYS);

        return user;

    }

/*    //根据token从redis获取当前登录用户
    private User findUserByToken(String token) {
        String user_json = stringRedisTemplate.opsForValue().get("TOKEN_" + token);
        User user = JSON.parseObject(user_json, User.class);
        //token失效时间一天
        stringRedisTemplate.opsForValue().set("TOKEN_"+token,user_json,1,TimeUnit.DAYS);
        return user;
    }*/



    //查找用户by Phone
    public ResponseEntity findByphone(String phone) {
        User user = userApi.findPhone(phone);
        //ResponseEntity标识整个http相应：状态码、头部信息以及相应体内容
        return ResponseEntity.ok(user);
    }


    public ResponseEntity saveUser(User user){
        Long id = userApi.save(user);
        return ResponseEntity.ok(id);
    }


/*    @PostMapping(name = "手机号发短信",value = "/login")*/
    public ResponseEntity login(String phone){
        //发短信
        //String code = RandomUtil.randomNumbers(6);

/*
        smsTemplate.sendSms(phone,code);
*/
        //验证码放入redis中
        String code="000000";
        stringRedisTemplate.opsForValue().set("SMS_CODE_"+phone,code, Duration.ofMinutes(5));

        System.out.println("验证码: "+code);
        return ResponseEntity.ok(null);
    }


    public ResponseEntity loginVerification(String phone,String verificationCode){

        //2 就页面用户填写的验证码和redis的验证码对比
        String code = stringRedisTemplate.opsForValue().get("SMS_CODE_" + phone);
        if(!StrUtil.equals(verificationCode,code)){
            //不一致
            return ResponseEntity.status(500).body("验证码错误");
        }

        // (带着手机号去数据库查询是否有该用户)
        User loginUser = userApi.findPhone(phone);


        //初始值（老用户）
        Boolean isNew=false;


        if(loginUser==null){
            //新用户(注册)
            loginUser = new User();
            loginUser.setPassword(SecureUtil.md5("123456"));
            loginUser.setPhone(phone);

            //注册为探花用户
            Long id = userApi.save(loginUser);//save方法会返回一个id
            huanXinTemplate.register(id);   //新用户注册成环信用户
            loginUser.setId(id);//user保存此id
            isNew=true;

        }


        //登录成功删除验证码
        stringRedisTemplate.delete("SMS_CODE_" + phone);

        log.debug(phone);


        //对老/新用户的数据做加密生成一串字符串（token）
        String token = JwtUtil.createToken(phone, loginUser.getId(), "tanhua");

        log.debug("token为: "+token);

        //转化为json格式 并将token和用户数据放入redis中
        String user_json = JSON.toJSONString(loginUser);
        stringRedisTemplate.opsForValue().set("TOKEN_"+token,user_json,1, TimeUnit.DAYS);

        // 设定返回值
        Map returnMap=new HashMap();
        //token响应给app保存
        returnMap.put("token",token);
        returnMap.put("isNew",isNew);
        return ResponseEntity.ok(returnMap);
    }


    public ResponseEntity loginReginfo(UserInfo userInfo, String token) {

        //根据token从redis获取当前登录用户
        User user=fromRedisUser(token);
        userInfo.setId(user.getId());

        //此时是没有头像地址的
        userInfoApi.save(userInfo);
        return ResponseEntity.ok(null);
    }




    public ResponseEntity loginReginfoimg(MultipartFile headPhoto, String token) throws IOException {
        //1 判断人脸识别
        boolean flag = aipFaceTemplate.detect(headPhoto.getBytes());
        if (!flag) {
            //识别失败
            return ResponseEntity.status(500).body("人脸识别失败！！！");
        }
        //2 上传图片到oss 记录地址
        String imgUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //3 根据token获取登录用户

        User user = UserHolder.getUser();//拦截器+线程池 优化 token可以删了
        //User user1 = fromRedisUser(token);
        //4 设置userInfo的id且根据id做修改

        UserInfo userInfo = new UserInfo();
        userInfo.setAvatar(imgUrl);
        userInfo.setCoverPic(imgUrl);
        userInfo.setId(user.getId());
        userInfoApi.update(userInfo);
        //返回
        return ResponseEntity.ok(null);
    }


    //数据回显
    public ResponseEntity findUserInfo(Long id) {
        UserInfo userInfo=userInfoApi.findUserInfo(id);
        //userInfo-UserInfoVo
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtil.copyProperties(userInfo,userInfoVo);

        //单独封装integer类型的age
        userInfoVo.setAge(userInfo.getAge().toString());
        return ResponseEntity.ok(userInfoVo);
    }

    //用户数据更新
    public ResponseEntity updateInfo(String token, UserInfo userInfo) {
        User user = fromRedisUser(token);
        userInfo.setId(user.getId());
        userInfoApi.update(userInfo);
        return ResponseEntity.ok(null);
    }

    //互相喜欢，喜欢，粉丝 - 人数统计
    public ResponseEntity counts() {
        // 1 查询互相喜欢的count
        long eachLoveCount=friendsApi.findeachLoveCount(UserHolder.getUser().getId());

        //2 查询喜欢的count
        long loveCount=userLikeApi.findloveCount(UserHolder.getUser().getId());

        //3 查询粉丝的count
        long fanCount=userLikeApi.findfanCount(UserHolder.getUser().getId());

        //4 封装vo返回
        CountsVo vo = new CountsVo(eachLoveCount, loveCount, fanCount);

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findBytype(Integer page, Integer pagesize, Integer type) {
        PageBeanVo pageBean=null;

        List<UserLikeListVo> voList=new ArrayList<>();
        switch (type){
            case 1:{
                // 查询相互喜欢的数据
                pageBean=friendsApi.findeachLovePage(page,pagesize,UserHolder.getUser().getId());
                List<Friend> items = (List<Friend>) pageBean.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (Friend friend : items) {
                        //userInfo
                        UserInfo userInfo = userInfoApi.findUserInfo(friend.getFriendId());
                        //封装
                        UserLikeListVo vo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo,vo);
                        Long score = recommentApi.findScore(UserHolder.getUser().getId(), friend.getFriendId());
                        vo.setMatchRate(score.intValue()); //缘分

                        voList.add(vo);
                    }
                }
                break;
            }
            case 2:{
                // 查询用户喜欢人的数据
                pageBean=userLikeApi.findUserLikeList(page,pagesize,UserHolder.getUser().getId());
                List<UserLike> items = (List<UserLike>) pageBean.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (UserLike userLike : items) {
                        //userInfo
                        UserInfo userInfo = userInfoApi.findUserInfo(userLike.getLikeUserId());
                        //封装
                        UserLikeListVo vo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo,vo);
                        Long score = recommentApi.findScore(UserHolder.getUser().getId(), userLike.getLikeUserId());
                        vo.setMatchRate(score.intValue()); //缘分

                        voList.add(vo);
                    }
                }
                break;
            }
            case 3:{
                // 查询粉丝的数据
                pageBean=userLikeApi.findLikeUserList(page,pagesize,UserHolder.getUser().getId());
                List<UserLike> items = (List<UserLike>) pageBean.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (UserLike userLike : items) {
                        //userInfo
                        UserInfo userInfo = userInfoApi.findUserInfo(userLike.getUserId());
                        //封装
                        UserLikeListVo vo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo,vo);
                        Long score = recommentApi.findScore(UserHolder.getUser().getId(), userLike.getUserId());
                        vo.setMatchRate(score.intValue()); //缘分

                        voList.add(vo);
                    }
                }
                break;
            }
            case 4:{
                // 查询历史访客的数据
                pageBean= visitorsApi.findVisitorsList(page,pagesize,UserHolder.getUser().getId());
                List<Visitors> items = (List<Visitors>) pageBean.getItems();
                if(CollectionUtil.isNotEmpty(items)){
                    for (Visitors visitors : items) {
                        //userInfo
                        UserInfo userInfo = userInfoApi.findUserInfo(visitors.getVisitorUserId());
                        //封装
                        UserLikeListVo vo = new UserLikeListVo();
                        BeanUtils.copyProperties(userInfo,vo);
                        Long score = recommentApi.findScore(UserHolder.getUser().getId(), visitors.getVisitorUserId());
                        vo.setMatchRate(score.intValue()); //缘分

                        voList.add(vo);
                    }
                }
                break;
            }
        }

        pageBean.setItems(voList);

        return ResponseEntity.ok(pageBean);

    }


    public ResponseEntity fansToFriend(Long fansId) {

        // 1 friend中多2条数据（增）
        friendsApi.contacts(fansId,UserHolder.getUser().getId());

        //2 user_like少一条数据（删）
        userLikeApi.removeFans(fansId,UserHolder.getUser().getId());
        return ResponseEntity.ok(null);

    }

    public ResponseEntity FriendTofans(Long loveId) {

        // 判断是互相好友的取消还是喜欢的取消
        Boolean flg=friendsApi.isFriend(UserHolder.getUser().getId(),loveId);
        if(flg){
            // 互相好友-->删除2条friend数据 userLike添加一条粉丝数据
            friendsApi.removeFriend(UserHolder.getUser().getId(),loveId);
            userLikeApi.addUserLike(UserHolder.getUser().getId(),loveId);
        }else{
            // 喜欢--->自己删除该用户 不做舔狗
            userLikeApi.removeFans(UserHolder.getUser().getId(),loveId);
        }

        return ResponseEntity.ok(null);
    }
}
